#include <boost/filesystem.hpp>
#include <iostream>
#include <stdio.h>

/*
 * delete_file_and_dir : 删除指定路径下文件和目录，保留指定个数的新文件
 *  @path - 路径
 *  @reserved_quantity - 保留新文件个数
 */
int delete_file_and_dir(const std::string &path, int reserved_quantity) {
    std::string cmd;
    std::vector<boost::filesystem::path> __file;
    int res;
    int count = 0;

    if (!boost::filesystem::is_directory(path)) {
        printf("path %s error\n", path.c_str());
        return -1;
    }
    for (auto file : boost::filesystem::directory_iterator(path)) {
        __file.push_back(file.path());
    }

    printf("folder %s have files [%ld], delete to [%d]\n",
                    path.c_str(), __file.size(), reserved_quantity);

    count = __file.size();
    while (count-- > 0) {  /* avoid a dead loop */
        __file.clear();
        for (auto file : boost::filesystem::directory_iterator(path)) {
            __file.push_back(file.path());
        }

        if (static_cast<int>(__file.size()) <= reserved_quantity) {
            break;
        }

        /* 按照修改时间排序，新文件在前 */
        sort(__file.begin(), __file.end(),
                    [](const boost::filesystem::path &a, const boost::filesystem::path &b)->bool {
                        std::time_t t1 = boost::filesystem::last_write_time(a);
                        std::time_t t2 = boost::filesystem::last_write_time(b);
                        return t1 > t2;
                    });

        auto it = --__file.end();

        /* delete directory */
        if (boost::filesystem::is_directory(*it)) {  
            cmd = "rm -rf " + it->string();
            printf("cmd:%s\n", cmd.c_str());
            system(cmd.c_str());
        }
        /* delete file */
        else {
            if (res = remove(it->string().c_str()), 0 == res) {
                printf("delet file {%s}\n", it->string().c_str());
                __file.erase(it);
            } else {
                printf("delete file {%s} failed\n", it->string().c_str());
                return -1;
            }
        }
    }

    return 0;
}

int main(void)
{
    std::string path = "/home/share/work/ac-code/test-verification/functional/dir/ac-test";

    /* 保留最新3个文件 */
	delete_file_and_dir(path, 3);

	return 0;
}

#if 0

同步系统上的软件包列表
sudo apt-update

整个库安装:
sudo apt-get install libboost-all-dev

安装部分库:
sudo apt-get install libboost-thread-dev
sudo apt-get install libboost-filesystem-dev

链接时加上:
-lboost_filesystem -lboost_system

例如:
g++ -Wall -o boost-clear-dir boost-clear-dir.o -lboost_filesystem

#endif

